package com.fingard.dsp.bank.helpers.dbhelpers;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import com.fingard.constant.Format;


public class LoadHelper {

	/**从数据库查出数据，并装载对象
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws ParseException */
	public static void loadObject(Map<String,Object> pMap, Object pClass) throws IllegalArgumentException, IllegalAccessException, ParseException{
		if(pMap!=null && pMap.size() > 0){
			Field[] fields = pClass.getClass().getFields();
			for(int i=0;i<fields.length;i++){
				String eachType = fields[i].getGenericType().toString().toLowerCase();
				String cName = fields[i].getName().toUpperCase();
				if(pMap.containsKey(cName) && pMap.get(cName)!=null){
					String eachVal = pMap.get(cName).toString();
					if("int".equals(eachType) || eachType.contains("integer")){
						if(eachVal.length() > 0){
							fields[i].set(pClass, Integer.parseInt(eachVal));
						}
					}else if("bigdecimal".equals(eachType) || eachType.contains("bigdecimal")){
						if(eachVal.length() > 0){
							fields[i].set(pClass, new BigDecimal(eachVal));
						}
					}else if(eachType.contains("double")){
						if(eachVal.length() > 0){
							fields[i].set(pClass, Double.parseDouble(eachVal));
						}
					}else if(eachType.contains("float")){
						if(eachVal.length() > 0){
							fields[i].set(pClass, Float.parseFloat(eachVal));
						}
					}else if(eachType.contains("boolean")){
						eachVal = eachVal.toLowerCase();
						if("1".equals(eachVal)||"true".equals(eachVal)){
							fields[i].set(pClass, true);
						}else{
							fields[i].set(pClass, false);
						}
					}else if(eachType.contains("date")){
						String val = pMap.get(cName).toString();
						if(val.contains("-") && val.contains(":")){
							fields[i].set(pClass, new SimpleDateFormat(Format.DateIsoFormatStr).parse(val));
						}
					}else if(eachType.contains("long")){
						if(eachVal.length() > 0){
							fields[i].set(pClass, Long.parseLong(pMap.get(cName).toString()));
						}
					}else if(eachType.contains("short")){
						if(eachVal.length() > 0){
							fields[i].set(pClass, Short.parseShort(pMap.get(cName).toString()));
						}
					}else{
						fields[i].set(pClass, pMap.get(cName));
					}
				}
			}
		}
	}
}
